package com.clusterswisdom.horn.api.db;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;

public class SaveLog {
	
	public static final String TYPE_EXCEPTION = "exception";

	public Long insertLog(Connection conn, String channel, String ip, String url, String param) throws SQLException {
		PreparedStatement statement = conn.prepareStatement(getInsertSql());
		statement.setString(1, channel);
		statement.setString(2, ip);
		statement.setString(3, url);
		statement.setString(4, param);
		statement.setTimestamp(5, new Timestamp(System.currentTimeMillis()));
		
		statement.executeUpdate();
		return getInsertId(conn);
	}
	
	public void updateLog(Connection conn, Long logId, String type, String response) throws SQLException {
		PreparedStatement statement = conn.prepareStatement(getUpdateSql());
		statement.setTimestamp(1, new Timestamp(System.currentTimeMillis()));
		statement.setString(2, type);
		statement.setString(3, response);
		statement.setLong(4, logId);
		
		statement.executeUpdate();
	}
	
	private String getInsertSql() {
		StringBuilder connBuilder = new StringBuilder(100);
		connBuilder.append("insert into t_request_log (client_channel, client_ip, request_uri, request_params, request_time)");
		connBuilder.append(" values (?, ?, ?, ?, ?)");
		return connBuilder.toString();
	}
	
	private String getUpdateSql() {
		StringBuilder connBuilder = new StringBuilder(100);
		connBuilder.append("update t_request_log set response_time = ?, response_type = ?, response_content = ?");
		connBuilder.append(" where id = ?");
		
		return connBuilder.toString();
	}
	
	private Long getInsertId(Connection conn) throws SQLException {
		Statement statement = conn.createStatement();
		ResultSet resultSet = statement.executeQuery("select last_insert_id()");
		if (resultSet.next()) {
			return resultSet.getLong(1);

		} else {
			return null;

		}
	}
}
